package com.linfeng.api.redis.listener;

import cn.hutool.core.util.StrUtil;
import com.linfeng.api.redis.config.RedisConfigProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;

/**
 * @author linfeng
 * @date 2021/1/13 14:03
 */

@Configuration
public class RedisListenerConfig {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RedisConfigProperties redisConfigProperties;

    @Bean
    RedisMessageListenerContainer container(RedisConnectionFactory factory) {
        String topic =StrUtil.format("__keyevent@{}__:expired", redisConfigProperties.getDatabase());
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(factory);
        container.addMessageListener(new RedisKeyExpirationListener(redisTemplate,redisConfigProperties), new PatternTopic(topic));
        return container;
    }

}
